package com.appupdate;

import android.app.AlertDialog;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.fileopener.R;

/**
 * @author weifu.zhang
 */
public class AppUpdateDialog {
    AlertDialog dialog;

    TextView txtContent;

    Button btnUpdate;
    ImageButton btnClose;
    ProgressBar progressLoading;

    public void showDialog(Context context, String message,boolean cancelable, final UpdateCallback updateCallback) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        LayoutInflater inflater = LayoutInflater.from(context);

        View view = inflater.inflate(R.layout.app_update_dialog, null);
        txtContent = view.findViewById(R.id.txtContent);
        txtContent.setText(message);

        btnUpdate = view.findViewById(R.id.btnUpdate);
        btnClose = view.findViewById(R.id.btnClose);
        progressLoading = view.findViewById(R.id.progressLoading);

        builder.setView(view);

        dialog = builder.create();

        if(!cancelable) {
            btnClose.setVisibility(View.GONE);
        }else{
            btnClose.setVisibility(View.VISIBLE);
            btnClose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    updateCallback.callback(-1);
                    dialog.dismiss();
                }
            });
        }
        btnUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                v.setVisibility(View.GONE);
                progressLoading.setVisibility(View.VISIBLE);
                updateCallback.callback(0);
            }
        });
        dialog.setCancelable(false);
        dialog.show();
    }

    public void closeDialog(){
        if(dialog!=null){
            dialog.dismiss();
        }
    }

    //    public void updateProgress(int percent){
//        progressLoading.setProgress(percent);
//    }

    public void updateProgress(int progress, int maxValue) {
        if (maxValue == 0) {
            return;
        }
        progressLoading.setMax(maxValue);
        progressLoading.setProgress(progress);
    }

    public interface UpdateCallback{
        void callback(int state);
    }
}
